<template>
  <div class="excellent-labeler-page">
    <div class="page-header">
      <h2>优秀标注员荣誉榜</h2>
      <div class="header-actions">
        <el-button type="primary" @click="showAddDialog">新增</el-button>
        <el-button type="success" @click="handleRefreshRanking">刷新排名</el-button>
      </div>
    </div>

    <!-- 查询条件 -->
    <div class="query-area">
      <el-form :model="queryForm" inline size="small">
        <el-form-item label="统计年份">
          <el-input-number
            v-model="queryForm.statYear"
            :min="2020"
            :max="2030"
            placeholder="请输入年份"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="统计月份">
          <el-select v-model="queryForm.statMonth" placeholder="请选择月份" clearable>
            <el-option
              v-for="month in 12"
              :key="month"
              :label="month + '月'"
              :value="month"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 数据表格 -->
    <div class="table-area">
      <el-table
        :data="tableData"
        border
        stripe
        v-loading="tableLoading"
        style="width: 100%"
      >
        <el-table-column type="index" label="序号" width="60" align="center"></el-table-column>
        <el-table-column prop="labelerName" label="标注员姓名" width="120" align="center"></el-table-column>
        <el-table-column prop="annotationCount" label="标注数量" width="100" align="center"></el-table-column>
        <el-table-column prop="statYear" label="统计年份" width="100" align="center"></el-table-column>
        <el-table-column prop="statMonth" label="统计月份" width="100" align="center">
          <template slot-scope="scope">
            {{ scope.row.statMonth }}月
          </template>
        </el-table-column>
        <el-table-column prop="ranking" label="排名" width="80" align="center">
          <template slot-scope="scope">
            <el-tag :type="getRankingTagType(scope.row.ranking)">
              {{ scope.row.ranking }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" align="center" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="text" size="small" style="color: #f56c6c" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pagination.currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pagination.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
        style="margin-top: 20px; text-align: right"
      >
      </el-pagination>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="labelerForm"
        :model="formData"
        :rules="formRules"
        label-width="120px"
      >
        <el-form-item label="标注员姓名" prop="labelerName">
          <el-input
            v-model="formData.labelerName"
            placeholder="请输入标注员姓名"
          ></el-input>
        </el-form-item>

        <el-form-item label="标注数量" prop="annotationCount">
          <el-input-number
            v-model="formData.annotationCount"
            :min="0"
            placeholder="请输入标注数量"
            style="width: 100%"
          ></el-input-number>
        </el-form-item>

        <el-form-item label="统计年份" prop="statYear">
          <el-input-number
            v-model="formData.statYear"
            :min="2020"
            :max="2030"
            placeholder="请输入统计年份"
            style="width: 100%"
          ></el-input-number>
        </el-form-item>

        <el-form-item label="统计月份" prop="statMonth">
          <el-select v-model="formData.statMonth" placeholder="请选择统计月份" style="width: 100%">
            <el-option
              v-for="month in 12"
              :key="month"
              :label="month + '月'"
              :value="month"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="排名" prop="ranking">
          <el-input-number
            v-model="formData.ranking"
            :min="1"
            placeholder="请输入排名"
            style="width: 100%"
          ></el-input-number>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确定</el-button>
      </div>
    </el-dialog>

    <!-- Excel批量导入预留区域 -->
    <div class="batch-import-area">
      <div class="import-header">
        <h3>Excel批量导入</h3>
        <el-button type="primary" size="small" @click="downloadTemplate">
          <i class="el-icon-download"></i> 下载导入模板
        </el-button>
      </div>
      
      <el-upload
        class="upload-demo"
        drag
        action=""
        :auto-upload="false"
        :on-change="handleFileChange"
        :on-remove="handleFileRemove"
        :file-list="fileList"
        :limit="1"
        accept=".xlsx,.xls"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将Excel文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip">只支持.xlsx或.xls格式的Excel文件，文件大小不超过10MB</div>
      </el-upload>
      
      <!-- 文件预览区域 -->
      <div v-if="selectedFile" class="file-preview">
        <div class="preview-header">
          <i class="el-icon-document"></i>
          <span class="file-name">{{ selectedFile.name }}</span>
          <span class="file-size">({{ formatFileSize(selectedFile.size) }})</span>
          <el-button 
            type="danger" 
            size="mini" 
            icon="el-icon-delete" 
            circle 
            @click="removeFile"
            title="删除文件"
          ></el-button>
        </div>
        <div class="preview-info">
          <p><i class="el-icon-info"></i> 文件已选择，点击"批量导入"按钮开始导入</p>
        </div>
              
        <!-- Excel内容预览 -->
        <div v-if="excelData.length > 0" class="excel-preview">
          <h4>数据预览（前10行）</h4>
          <el-table
            :data="excelData"
            border
            size="small"
            max-height="400"
            style="width: 100%"
          >
            <el-table-column type="index" label="行号" width="60" align="center"></el-table-column>
            <el-table-column prop="labelerName" label="标注员姓名" width="120" align="center"></el-table-column>
            <el-table-column prop="annotationCount" label="标注数量" width="100" align="center"></el-table-column>
            <el-table-column prop="statYear" label="统计年份" width="100" align="center"></el-table-column>
            <el-table-column prop="statMonth" label="统计月份" width="100" align="center">
              <template slot-scope="scope">
                {{ scope.row.statMonth }}月
              </template>
            </el-table-column>
            <el-table-column prop="ranking" label="排名" width="80" align="center"></el-table-column>
          </el-table>
          <div class="preview-tip">
            <i class="el-icon-warning"></i> 共读取到 <strong>{{ totalExcelRows }}</strong> 行数据，上表仅展示前10行，请核对数据后点击"批量导入"
          </div>
        </div>
      </div>
      
      <el-button 
        type="success" 
        style="margin-top: 10px;" 
        @click="handleImport"
        :loading="importLoading"
        :disabled="!selectedFile"
      >
        <i class="el-icon-upload2"></i> {{ importLoading ? '导入中...' : '批量导入' }}
      </el-button>
    </div>

    <!-- 导入结果对话框 -->
    <el-dialog
      title="导入结果"
      :visible.sync="importResultVisible"
      width="600px"
    >
      <div class="import-result">
        <el-alert
          :type="importResult.failRows > 0 ? 'warning' : 'success'"
          :closable="false"
          style="margin-bottom: 20px"
        >
          <template slot="title">
            <div class="result-summary">
              <p>总行数：<strong>{{ importResult.totalRows }}</strong></p>
              <p style="color: #67C23A">成功：<strong>{{ importResult.successRows }}</strong></p>
              <p style="color: #F56C6C">失败：<strong>{{ importResult.failRows }}</strong></p>
            </div>
          </template>
        </el-alert>
        
        <div v-if="importResult.errorMessages && importResult.errorMessages.length > 0" class="error-list">
          <h4>错误详情：</h4>
          <el-scrollbar style="height: 300px">
            <ul>
              <li v-for="(error, index) in importResult.errorMessages" :key="index" class="error-item">
                {{ error }}
              </li>
            </ul>
          </el-scrollbar>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="importResultVisible = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { 
  getExcellentLabelerAPI, 
  addExcellentLabelerAPI, 
  updateExcellentLabelerAPI, 
  deleteExcellentLabelerAPI, 
  downloadExcellentLabelerTemplateAPI, 
  importExcellentLabelerExcelAPI,
  refreshLabelerRankingAPI
} from '@/api/admin';
import * as XLSX from 'xlsx';

export default {
  name: 'ExcellentLabeler',
  data() {
    return {
      dialogVisible: false,
      dialogTitle: '新增优秀标注员记录',
      submitLoading: false,
      // 查询表单
      queryForm: {
        statYear: new Date().getFullYear(),  // 默认当前年份
        statMonth: null                      // 月份
      },
      // 表格数据
      tableData: [],
      tableLoading: false,
      // 分页
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      // 表单数据
      formData: {
        labelerName: '',        // 标注员姓名
        annotationCount: null,  // 标注数量
        statYear: new Date().getFullYear(),  // 统计年份
        statMonth: null,        // 统计月份
        ranking: null           // 排名
      },
      formRules: {
        labelerName: [
          { required: true, message: '请输入标注员姓名', trigger: 'blur' }
        ],
        annotationCount: [
          { required: true, message: '请输入标注数量', trigger: 'blur' }
        ],
        statYear: [
          { required: true, message: '请输入统计年份', trigger: 'blur' }
        ],
        statMonth: [
          { required: true, message: '请选择统计月份', trigger: 'change' }
        ],
        ranking: [
          { required: true, message: '请输入排名', trigger: 'blur' }
        ]
      },
      // Excel导入相关
      selectedFile: null,
      fileList: [],  // 文件列表
      excelData: [],  // Excel数据预览
      totalExcelRows: 0,  // 总行数
      importLoading: false,
      importResultVisible: false,
      importResult: {
        totalRows: 0,
        successRows: 0,
        failRows: 0,
        errorMessages: []
      }
    };
  },
  mounted() {
    // 页面加载时查询数据
    this.getTableData();
  },
  methods: {
    // 获取排名标签类型
    getRankingTagType(ranking) {
      if (ranking === 1) return 'danger';
      if (ranking === 2) return 'warning';
      if (ranking === 3) return 'success';
      return 'info';
    },
    
    // 查询数据
    handleQuery() {
      this.pagination.currentPage = 1;
      this.getTableData();
    },
    
    // 重置查询
    handleReset() {
      this.queryForm = {
        statYear: new Date().getFullYear(),
        statMonth: null
      };
      this.pagination.currentPage = 1;
      this.getTableData();
    },
    
    // 获取表格数据
    getTableData() {
      this.tableLoading = true;
      
      // 构建查询参数
      const params = {
        currentPage: this.pagination.currentPage,
        pageSize: this.pagination.pageSize
      };
      
      if (this.queryForm.statYear) {
        params.statYear = this.queryForm.statYear;
      }
      
      if (this.queryForm.statMonth) {
        params.statMonth = this.queryForm.statMonth;
      }
      
      // 调用后端接口查询数据
      getExcellentLabelerAPI(params).then(res => {
        this.tableLoading = false;
        if (res.code === 200) {
          this.tableData = res.data.records || [];
          this.pagination.total = res.data.total || 0;
          this.pagination.currentPage = res.data.currentPage || 1;
          this.pagination.pageSize = res.data.pageSize || 10;
        } else {
          this.$message.error(res.message || '查询失败');
        }
      }).catch(error => {
        this.tableLoading = false;
        this.$message.error('查询失败，请检查网络');
        console.error('查询错误:', error);
      });
    },
    
    // 编辑
    handleEdit(row) {
      this.dialogTitle = '编辑优秀标注员记录';
      this.formData = { ...row };
      this.dialogVisible = true;
    },
    
    // 删除
    handleDelete(row) {
      this.$confirm('确认删除该条数据吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 调用后端删除接口
        deleteExcellentLabelerAPI(row.id).then(res => {
          if (res.code === 200) {
            this.$message.success('删除成功');
            this.getTableData();
          } else {
            this.$message.error(res.message || '删除失败');
          }
        }).catch(error => {
          this.$message.error('删除失败，请检查网络');
          console.error('删除错误:', error);
        });
      }).catch(() => {});
    },
    
    // 分页 - 每页条数改变
    handleSizeChange(val) {
      this.pagination.pageSize = val;
      this.pagination.currentPage = 1;
      this.getTableData();
    },
    
    // 分页 - 当前页改变
    handleCurrentChange(val) {
      this.pagination.currentPage = val;
      this.getTableData();
    },
    
    // 显示新增对话框
    showAddDialog() {
      this.dialogTitle = '新增优秀标注员记录';
      this.resetForm();
      this.dialogVisible = true;
    },
    
    // 重置表单
    resetForm() {
      this.formData = {
        labelerName: '',
        annotationCount: null,
        statYear: new Date().getFullYear(),
        statMonth: null,
        ranking: null
      };
      if (this.$refs.labelerForm) {
        this.$refs.labelerForm.resetFields();
      }
    },
    
    // 提交表单
    handleSubmit() {
      this.$refs.labelerForm.validate((valid) => {
        if (valid) {
          this.submitLoading = true;
          
          // 判断是新增还是编辑
          const isEdit = !!this.formData.id;
          const apiCall = isEdit 
            ? updateExcellentLabelerAPI(this.formData.id, this.formData)
            : addExcellentLabelerAPI(this.formData);
          
          apiCall.then(res => {
            this.submitLoading = false;
            if (res.code === 200) {
              this.$message.success(isEdit ? '修改成功' : '新增成功');
              this.dialogVisible = false;
              this.resetForm();
              // 刷新列表
              this.getTableData();
            } else {
              this.$message.error(res.message || '操作失败');
            }
          }).catch(error => {
            this.submitLoading = false;
            this.$message.error('操作失败，请检查网络');
            console.error('提交错误:', error);
          });
        }
      });
    },
    
    // 处理文件上传
    handleFileChange(file, fileList) {
      // 验证文件类型
      const isExcel = file.raw.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
                   || file.raw.type === 'application/vnd.ms-excel';
      const isLt10M = file.size / 1024 / 1024 < 10;

      if (!isExcel) {
        this.$message.error('只能上传Excel文件！');
        // 移除非法文件
        this.fileList = [];
        return false;
      }
      if (!isLt10M) {
        this.$message.error('文件大小不能超过10MB！');
        // 移除超大文件
        this.fileList = [];
        return false;
      }
      
      this.selectedFile = file.raw;
      this.fileList = [file];
      
      // 解析Excel文件并预览
      this.parseExcelFile(file.raw);
    },
    
    // 解析Excel文件
    parseExcelFile(file) {
      const reader = new FileReader();
      reader.onload = (e) => {
        try {
          const data = new Uint8Array(e.target.result);
          const workbook = XLSX.read(data, { type: 'array' });
          
          // 读取第一个sheet
          const firstSheetName = workbook.SheetNames[0];
          const worksheet = workbook.Sheets[firstSheetName];
          
          // 转换为JSON数据
          const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });
          
          // 过滤表头和空行
          const dataRows = jsonData.slice(1).filter(row => row && row.length > 0);
          this.totalExcelRows = dataRows.length;
          
          // 转换为对象数组（只取前10行）
          this.excelData = dataRows.slice(0, 10).map(row => ({
            labelerName: row[0] || '',      // 标注员姓名
            annotationCount: row[1] || 0,   // 标注数量
            statYear: row[2] || 0,          // 统计年份
            statMonth: row[3] || 0,         // 统计月份
            ranking: row[4] || 0            // 排名
          }));
          
          this.$message.success(`文件解析成功，共${this.totalExcelRows}行数据`);
        } catch (error) {
          console.error('Excel解析错误:', error);
          this.$message.error('Excel文件解析失败，请检查文件格式');
          this.excelData = [];
          this.totalExcelRows = 0;
        }
      };
      reader.readAsArrayBuffer(file);
    },
    
    // 删除文件（通过上传组件的删除按钮）
    handleFileRemove(file, fileList) {
      this.selectedFile = null;
      this.fileList = [];
      this.excelData = [];
      this.totalExcelRows = 0;
      this.$message.info('文件已移除');
    },
    
    // 手动删除文件
    removeFile() {
      this.selectedFile = null;
      this.fileList = [];
      this.excelData = [];
      this.totalExcelRows = 0;
      this.$message.info('文件已移除，可以重新上传');
    },
    
    // 格式化文件大小
    formatFileSize(bytes) {
      if (bytes === 0) return '0 B';
      const k = 1024;
      const sizes = ['B', 'KB', 'MB', 'GB'];
      const i = Math.floor(Math.log(bytes) / Math.log(k));
      return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i];
    },
    
    // 下载模板
    downloadTemplate() {
      this.$message.info('正在下载模板...');
      downloadExcellentLabelerTemplateAPI().then(res => {
        // 创建下载链接
        const blob = new Blob([res], { 
          type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
        });
        const url = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.download = '优秀标注员导入模板.xlsx';
        link.click();
        window.URL.revokeObjectURL(url);
        this.$message.success('模板下载成功');
      }).catch(error => {
        this.$message.error('模板下载失败');
        console.error('下载错误:', error);
      });
    },
    
    // 批量导入
    handleImport() {
      if (!this.selectedFile) {
        this.$message.warning('请先选择要导入的Excel文件');
        return;
      }
      
      this.importLoading = true;
      importExcellentLabelerExcelAPI(this.selectedFile).then(res => {
        this.importLoading = false;
        if (res.code === 200) {
          this.importResult = res.data;
          this.importResultVisible = true;
          
          // 导入成功后刷新列表
          if (res.data.successRows > 0) {
            this.getTableData();
          }
          
          // 清空文件选择和预览数据
          this.selectedFile = null;
          this.fileList = [];
          this.excelData = [];
          this.totalExcelRows = 0;
          
          if (res.data.failRows === 0) {
            this.$message.success(`导入完成！成功${res.data.successRows}条`);
          } else {
            this.$message.warning(`导入完成！成功${res.data.successRows}条，失败${res.data.failRows}条`);
          }
        } else {
          this.$message.error(res.message || '导入失败');
        }
      }).catch(error => {
        this.importLoading = false;
        this.$message.error('导入失败，请检查网络或文件格式');
        console.error('导入错误:', error);
      });
    },
    
    // 刷新排名
    handleRefreshRanking() {
      this.$confirm('确认刷新排名吗？系统将根据标注数量重新计算排名。', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const params = {
          statYear: this.queryForm.statYear || new Date().getFullYear()
        };
        
        if (this.queryForm.statMonth) {
          params.statMonth = this.queryForm.statMonth;
        }
        
        refreshLabelerRankingAPI(params).then(res => {
          if (res.code === 200) {
            this.$message.success('排名刷新成功');
            this.getTableData();
          } else {
            this.$message.error(res.message || '刷新失败');
          }
        }).catch(error => {
          this.$message.error('刷新失败，请检查网络');
          console.error('刷新错误:', error);
        });
      }).catch(() => {});
    }
  }
};
</script>

<style lang="scss" scoped>
.excellent-labeler-page {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    h2 {
      margin: 0;
      font-size: 20px;
      color: #333;
    }
    
    .header-actions {
      display: flex;
      gap: 10px;
    }
  }
  
  .batch-import-area {
    margin-top: 40px;
    padding: 20px;
    background: #f5f7fa;
    border-radius: 4px;
    
    .import-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 15px;
    }
    
    h3 {
      margin: 0;
      font-size: 16px;
      color: #333;
    }
    
    .upload-demo {
      width: 100%;
    }
    
    .file-preview {
      margin-top: 15px;
      padding: 15px;
      background: #fff;
      border: 1px solid #e4e7ed;
      border-radius: 4px;
      
      .preview-header {
        display: flex;
        align-items: center;
        gap: 10px;
        
        i.el-icon-document {
          font-size: 24px;
          color: #67c23a;
        }
        
        .file-name {
          flex: 1;
          font-size: 14px;
          font-weight: 500;
          color: #303133;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
        
        .file-size {
          font-size: 12px;
          color: #909399;
        }
      }
      
      .preview-info {
        margin-top: 10px;
        padding: 8px 12px;
        background: #ecf5ff;
        border-left: 3px solid #409eff;
        border-radius: 4px;
        
        p {
          margin: 0;
          font-size: 13px;
          color: #409eff;
          
          i {
            margin-right: 5px;
          }
        }
      }
      
      .excel-preview {
        margin-top: 20px;
        
        h4 {
          margin: 0 0 10px;
          font-size: 14px;
          color: #333;
          font-weight: 600;
        }
        
        .preview-tip {
          margin-top: 10px;
          padding: 8px 12px;
          background: #fff3cd;
          border-left: 3px solid #ffc107;
          border-radius: 4px;
          font-size: 13px;
          color: #856404;
          
          i {
            margin-right: 5px;
          }
          
          strong {
            color: #d9534f;
            font-size: 16px;
          }
        }
      }
    }
  }
  
  .import-result {
    .result-summary {
      display: flex;
      justify-content: space-around;
      
      p {
        margin: 5px 0;
        font-size: 14px;
        
        strong {
          font-size: 18px;
        }
      }
    }
    
    .error-list {
      margin-top: 20px;
      
      h4 {
        margin: 0 0 10px;
        font-size: 14px;
        color: #333;
      }
      
      ul {
        list-style: none;
        padding: 0;
        margin: 0;
      }
      
      .error-item {
        padding: 8px 12px;
        margin-bottom: 8px;
        background: #fef0f0;
        border-left: 3px solid #f56c6c;
        color: #f56c6c;
        font-size: 13px;
        border-radius: 4px;
      }
    }
  }
}

::v-deep .el-dialog__body {
  padding: 20px;
}

::v-deep .el-input-number {
  width: 100%;
}
</style>